import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.Collections;

/**
 * @author Lei
 * @create 2022-05-22 19:53
 */
public class HistoryPanel extends JPanel {
    private Library m;

    public HistoryPanel(Library m) {
        this.m = m;
    }

    private int historyMax(ArrayList<Integer> history) {
        return Collections.max(history);
    }

    private int historyMin(ArrayList<Integer> history) {
        return Collections.min(history);
    }

    private int historyRange(ArrayList<Integer> list) {
        return Math.max(historyMax(list) - historyMin(list), 10);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        ArrayList<Integer> history = m.getHistory();
        int min = historyMin(history);
        int range = historyRange(history);
        int maxX = getWidth() -1;
        int maxY = getHeight() -1;
        int zero = maxY + min * maxY / range ;
        g.setColor(new Color(0, 0, 255));
        g.drawLine(0, zero, maxX, zero);
        g.setColor(new Color(255, 0, 0));
        int preX = 0;
        int preY = zero;
        for (int i = 0; i < history.size(); i++) {
            int x = i * 10;
            int y = zero - history.get(i) * maxY / range ;
            g.drawRect(x, y, 1, 1);
            g.drawLine(preX, preY, x, y);
            preX = x;
            preY = y;
        }
    }
}
